package com.yunji.web.monitor;

import com.yunji.common.annotation.Log;
import com.yunji.common.base.BaseController;
import com.yunji.common.base.response.Response;
import com.yunji.common.base.response.ResponseHelper;
import com.yunji.common.constant.CacheCode;
import com.yunji.common.enums.common.BusinessType;
import com.yunji.common.model.domain.SysUserOnlineDO;
import com.yunji.common.model.dto.LoginInfo;
import com.yunji.common.utils.StringUtils;
import com.yunji.system.service.ISysUserOnlineService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.List;

/**
 * 在线用户监控
 *
 * @author ruoyi
 */
@Api(tags = "在线用户监控")
@RestController
@RequestMapping("/monitor/online")
public class SysUserOnlineController extends BaseController {
    @Autowired
    private ISysUserOnlineService userOnlineService;

    @ApiOperation("在线用户监控列表")
    @PreAuthorize("@ss.hasPermi('monitor:online:list')")
    @GetMapping("/list")
    public Response<List<SysUserOnlineDO>> list(String ipaddr, String userName) {
        Collection<String> keys = redisCache.keys(CacheCode.LOGIN_TOKEN_KEY + "*");
        List<SysUserOnlineDO> userOnlineList = new ArrayList<SysUserOnlineDO>();
        for (String key : keys) {
            LoginInfo user = redisCache.get(key);
            if (StringUtils.isNotNull(ipaddr) && StringUtils.isNotNull(userName)) {
                userOnlineList.add(userOnlineService.selectOnlineByInfo(ipaddr, userName, user));
            } else if (StringUtils.isNotNull(ipaddr)) {
                userOnlineList.add(userOnlineService.selectOnlineByIpaddr(ipaddr, user));
            } else if (StringUtils.isNotNull(userName) && StringUtils.isNotNull(user)) {
                userOnlineList.add(userOnlineService.selectOnlineByUserName(userName, user));
            } else {
                userOnlineList.add(userOnlineService.loginUserToUserOnline(user));
            }
        }
        Collections.reverse(userOnlineList);
        userOnlineList.removeAll(Collections.singleton(null));
        return ResponseHelper.successWithPage(userOnlineList);
    }

    /**
     * 强退用户
     */
    @ApiOperation("强退用户")
    @PreAuthorize("@ss.hasPermi('monitor:online:forceLogout')")
    @Log(title = "在线用户", businessType = BusinessType.FORCE)
    @DeleteMapping("/{tokenId}")
    public Response<String> forceLogout(@PathVariable String tokenId) {
        redisCache.delete(tokenId);
        return ResponseHelper.success();
    }
}
